#include "OpenFileDescTable.h"
using namespace std;


OpenFileDescTable::OpenFileDescTable()
{
	InitTable();
	_nextFreeFD = 0;
}

int OpenFileDescTable::getOffsetByFd(int fd)
{
	fileDesc f = _table[fd];
	return f.filePos;
}


int OpenFileDescTable::getInodeByFd(int fd)
{
	fileDesc f = _table[fd];
	return f.inode;
}

void OpenFileDescTable::moveFd(int fd, int newPos)
{
		fileDesc f = _table[fd];
		f.filePos = newPos;
		_table[fd] = f;
}
OpenFileDescTable:: ~OpenFileDescTable(){}

void OpenFileDescTable::InitTable()
{
	_table = map<int,fileDesc>();
}

// sets new fd to smallet possible
// returns true on success, false if full
bool OpenFileDescTable::setNextFD()
{
	for (int i = 0; i < maxFiles; ++i) {
		if (_table.count(i) == 0 ){
			_nextFreeFD = i;
			return true;
		}
	}
	return false;
}


void OpenFileDescTable::RemoveFile(int fd)
{
	if (_table.count(fd) == 0){ 			//no such fd
		cerr<<"trying to remove a free fd"<<endl;
	}
	else{
		_table.erase(fd);
	}
	setNextFD();
}


int OpenFileDescTable::AddFile(int inode,int perm)
{
	if (_table.size() == maxFiles)
	{
		cerr<<"cannot open any more files"<<endl;
	}
	else
	{
		int ans =_nextFreeFD;

		fileDesc f;
		f.filePos = 0;
		f.inode = inode;
		f.permissions = perm;

		_table[ans] = f;
		setNextFD();
		return ans;
	}
}
